package com.yfp.machine.service.impl;

import cn.hutool.core.util.NumberUtil;
import com.yfp.machine.domain.OrderList;
import com.yfp.machine.enums.OrderStatusEnum;
import com.yfp.machine.mapper.OrderListMapper;
import com.yfp.machine.service.OrderListService;
import jakarta.annotation.Resource;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import java.util.List;


/**
 * (Order)表服务实现类
 *
 *
 * @since 2023-12-14 14:39:54
 */
@Service("orderService")
public class OrderListListServiceImpl implements OrderListService {

    @Resource
    private OrderListMapper orderListMapper;

    /**
     * 通过ID查询单条数据
     *
     * @param orderSn 主键
     * @return 实例对象
     */
    @Override
    public OrderList queryById(String orderSn) {
        return this.orderListMapper.queryById(orderSn);
    }

    /**
     * 分页查询
     *
     * @param orderList       筛选条件
     * @param pageRequest 分页对象
     * @return 查询结果
     */
    @Override
    public Page<OrderList> queryByPage(OrderList orderList, PageRequest pageRequest) {
        long total = this.orderListMapper.count(orderList);
        return new PageImpl<>(this.orderListMapper.queryAllByLimit(orderList, pageRequest), pageRequest, total);
    }

    /**
     * 新增数据
     *
     * @param orderList 实例对象
     * @return 实例对象
     */
    @Override
    public OrderList insert(OrderList orderList) {
        this.orderListMapper.insert(orderList);
        return orderList;
    }

    /**
     * 修改数据
     *
     * @param orderList 实例对象
     * @return 实例对象
     */
    @Override
    public OrderList update(OrderList orderList) {
        this.orderListMapper.update(orderList);
        return this.queryById(orderList.getOrderSn());
    }

    /**
     * 通过主键删除数据
     *
     * @param orderSn 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(String orderSn) {
        return this.orderListMapper.deleteById(orderSn) > 0;
    }

    @Override
    public String queryMachineSalesAmount(String machineId) {
        OrderList order = new OrderList();
        order.setMachineId(machineId);
        order.setPayStatus(OrderStatusEnum.COMPLETED.getCode());
        List<OrderList> orderList = this.orderListMapper.selectListByCondition(order);

        String[] amtArr = orderList.stream().map(OrderList::getAmt).toArray(String []::new);
        return NumberUtil.add(amtArr).toString();
    }
}
